package com.jgp.sys.utils;

import com.jgp.common.persistence.TreeModelStructure;
import com.jgp.common.pojo.TreeBean;
import com.jgp.common.utils.JGPUtil;
import lombok.extern.log4j.Log4j2;

import java.util.*;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-11-01
 */
@Log4j2
public class TreeUtil {
    
    
    public static <M> List<TreeBean> createTree(List<M> models) {
        if(Objects.isNull(models)||models.size() == 0){
            return null;
        }
        List<TreeBean> var1 = new ArrayList<>(); //要返回的结果
        Map<String, List<TreeBean>> map = new TreeMap<>(); //将同级节点整合
        if(!TreeModelStructure.class.isAssignableFrom(models.get(0).getClass())){
            log.error(JGPUtil.toJson(models.get(0))+"\n非tree结构模型");
        }
        for (M model : models) {
            TreeModelStructure treeModel = (TreeModelStructure) model;
            String supers = treeModel.getSupers();
            int level = supers.split(",").length;
            TreeBean node = treeModel.mapping();
            node.setLevel(level);
            if(map.get(supers) != null) {
                map.get(supers).add(node);
            } else {
                List<TreeBean> var4 = new ArrayList<>();
                var4.add(node);
                map.put(supers, var4);
            }
        }
        
        //创建树
        createNodes(map,var1);
        return var1;
    }
    
    
    private static TreeBean createNode(Map<String, List<TreeBean>> map, TreeBean treeNode) {
        String parentKeys = treeNode.getSupers();
        
        if(map.containsKey(parentKeys)) {
            map.remove(parentKeys);
        }
        
        String supers = parentKeys + "," + treeNode.getKey();
        
        List<TreeBean> treeNodes = map.get(supers);
        if(treeNodes != null && treeNodes.size() > 0) {
            for (TreeBean node : treeNodes) {
                treeNode.getChildren().add(createNode(map, node));
            }
        }
        
        return treeNode;
    }
    
    private static List<TreeBean>  createNodes(Map<String, List<TreeBean>> map, List<TreeBean> treeNodes) {
        if(map.size() > 0) {
            List<TreeBean> nodeList = map.get(map.keySet().toArray()[0]);
            treeNodes.addAll(nodeList);
            map.remove(nodeList.get(0).getSupers());
            for (TreeBean node : nodeList) {
                createNode(map, node);
            }
            createNodes(map, treeNodes);
        }
        return treeNodes;
    }
}
